<?php
	header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

	// Includes
	require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/includes.php';
	
	

	// Create our Application instance
	$facebook = new Facebook(array(
		'appId'  => $GLOBALS['FACEBOOK']['ID'],
		'secret' => $GLOBALS['FACEBOOK']['SECRET'],
		'cookie' => true,
		'domain' => 'leedsmet.ac.uk'
	));
	
	// Ensure there is a session for this user and the app has been granted basic permissions
	$session = JanusFacebook::checkSessionAuth($facebook);
	$facebook_id = $facebook->getUser();
	
	if ($session)
	{
		try
		{
			$application = $facebook->api($GLOBALS['FACEBOOK']['ID']);
			$appName     = htmlspecialchars($application['name']);
		}
		catch (FacebookApiException $e)
		{
			error_log($e);
			$appName = '#unknown#';
		}
	}
	
	JanusFacebook::checkApiAccess($facebook);
	

	// Load tabs template. By default, detected replacement codes are replaced with an empty 
	// string so only those that are specified will be replaced with something useful. 
	$template = new MarkupTemplate();
	$template->loadTemplateFile($GLOBALS['TEMPLATES']['BASE_PATH'] . 'fb_tabs.tpl', true);
	$template->updateReplacement('ACCOUNT_TAB_SELECTED', 'selected', false);
	$tabContent = $template->getOutputMarkup();
	
	
	// Database connection 

	$errors = array();
	$err_messages = array();
	
	$conn = JanusDb::getDbConnection();

	// check valid connection and manage errors

	if ($conn === false)
	{
		$errors[] = oci_error();
		$err_messages[] = "The database connection failed. Please try later.";
	}
	else
	{
		// Check to see if the user is in the database - include check stuff
		$registration_status = JanusDb::checkUserExists($conn, $facebook_id);
	
		// If user is registered...
		
		if ($registration_status == false)
		{
			// Registration form, if user is not registered
			$template = new MarkupTemplate();
			$template->loadTemplateFile($GLOBALS['TEMPLATES']['BASE_PATH'] . 'registration_form.tpl', true);
			$template->updateReplacement('FACEBOOK_ID', $facebook_id);
			$pageContent = $template->getOutputMarkup();
			
			$display_user_information = false;		
		}
		else
		{
			/*
			AUTHENTICATION CODE TO CHECK IF USERNAME AND PIN ARE VALID COULD BE ADDED HERE
			
			POSITITVE RESULT -->
			*/
			
			// Create query to get users library id and pin
			$stid = @oci_parse($conn, "select LIBRARY_ID,PIN from JANUS where FACEBOOK_ID = :facebook_id");
			
			if (!$stid)
			{
				$errors[] = oci_error();
			}
			elseif (!@oci_bind_by_name($stid, ':facebook_id', $facebook_id))
			{
				$errors[] = oci_error();
			}
			elseif (!@oci_execute($stid, OCI_DEFAULT))
			{
				$errors[] = oci_error();
				$err_messages[] = "This service is currently unavailable, please try later";
			}
			else
			{
				/* Result */
				$result = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
			}
			
			$library_id = $result['LIBRARY_ID'];
			$pin = $result['PIN'];
			$display_user_information = true;
		}	
	} // End connection error handling
	
	if ($display_user_information == true)
	{
		$pageContent = JanusUtilityFuncs::getCurrentLoansMarkup($library_id);
		$pageContent = "<div class=\"generalBox\">\n$pageContent\n</div>\n";
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="/main/apps/janus/css/janus.css" type="text/css" />
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
/* <![CDATA */
	window.fbAsyncInit = function() {
		FB.init({
			appId   : '<?php echo $facebook->getAppId(); ?>',
			session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
			status  : true, // check login status
			cookie  : true, // enable cookies to allow the server to access the session
			xfbml   : true // parse XFBML
		});

		// whenever the user logs in, we refresh the page
		FB.Event.subscribe('auth.login', function() {
			window.location.reload();
		});

		// Parse any FBML
		//FB.XFBML.parse();
	};
	
	(function() {
		var e = document.createElement('script');
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}());
/* ]]> */
</script>
<h1><?php echo $appName; ?></h1>
<?php echo $tabContent; ?>
<?php echo $pageContent; ?>
</body>
</html>